package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    //添加套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setMAndC(checkgroupIds, setmealId);
        //将图片名称保存在Redis数据库中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        //添加套餐生成后所需的静态页面
        generateMobileStaticHtml();

    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        //生成静态页面之前查询所有数据
        List<Setmeal> setmeals = setmealDao.getSetmeal();

        //生成套餐列表页面
        generateMobileSetmealListHtml(setmeals);

        //生成套餐详情页面
        generateMobileSetmealDetailHtml(setmeals);
    }

    //生成套餐列表页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmeals) {
        Map map = new HashMap();
        map.put("setmealList", setmeals);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmeals) {
        for (Setmeal setmeal : setmeals) {
            Map map = new HashMap();
            map.put("setmeal", setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }

    }

    //抽取方法，用于生成静态页面
    public void generateHtml(String templateName, String htmlPageName, Map map) {
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //加载模板文件
        OutputStreamWriter outputStreamWriter = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //创建输出流，输出静态文件
            // writer=new FileWriter(new File(outPutPath+"/"+htmlPageName));
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outPutPath + "/" + htmlPageName), "utf-8");
            //输出文件
            template.process(map, outputStreamWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals = setmealDao.findByCondition(queryString);
        return new PageResult(setmeals.getTotal(), setmeals.getResult());
    }

    //删除套餐
    @Override
    public void delById(Integer id) {
        //查询t_setmeal_checkgroup表中套餐表是否被关联了，关联就删除关联再删除表中数据，没关联就直接删除
        long count = setmealDao.findCountInSC(id);
        //获取图片名字
        Setmeal setmeal = setmealDao.findSetmeal(id);
        String img = setmeal.getImg();
        if (count > 0) {
            setmealDao.delSC(id);
            setmealDao.delById(id);
            QiniuUtils.deleteFileFromQiniu(img);
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES, img);
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        } else {
            setmealDao.delById(id);
            QiniuUtils.deleteFileFromQiniu(img);
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES, img);
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        }
        generateMobileStaticHtml();
    }


    //查询所有套餐
    @Override
    public List<Setmeal> getSetmeal() {
        return setmealDao.getSetmeal();
    }

    //查询套餐的详情信息，包括基本信息，检查组信息，检查项信息
    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    //套餐预约人数占比饼图
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        //获取套餐的种类和人数
        List<Map<String, Object>> mapList = setmealDao.findSetmealCount();
        return mapList;
    }

    //抽取设置套餐和检查组的关联表
    public void setMAndC(Integer[] checkgroupIds, Integer setmealId) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<String, Integer>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setMAndC(map);
            }
        }
    }
}
